//
//  WebViewController.m
//  GiftItems
//
//  Created by lanou3g on 15/9/21.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "WebViewController.h"
#import "WebStrategyModel.h"
#import "BlurImageView.h"
#import "WebHeaderView.h"

#define ImageHight 200.0f
@interface WebViewController ()<UIWebViewDelegate,UIScrollViewDelegate>
@property (nonatomic,strong)NSMutableArray *webArray;
@property (nonatomic,strong) UIWebView *webView;
@property (nonatomic,strong) UIImageView *headerImage;
@property (nonatomic,strong) WebHeaderView *headerView;
@property (nonatomic,strong) NSString *shareUrl;

@property (nonatomic,strong) UIProgressView *progressView;

@property (nonatomic,assign)NSUInteger loadCount;


@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    //加载次数置0;
    self.loadCount = 0;
    
    //添加 webView
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
    self.webView.userInteractionEnabled = YES;
    self.webView.backgroundColor = [UIColor colorWithRed:250.0/255 green:250.0/255 blue:250.0/255 alpha:1];
    //添加webView代理
    self.webView.scrollView.delegate = self;
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    
    if ([self.type isEqualToString:@"攻略"]) {
        [self reloadWebData];
    }
    
    //添加headerView
    self.headerView = [[WebHeaderView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 64)];
    self.headerView.backgroundColor = kRGB(255.0, 151.0, 255.0);
    [self.view addSubview:self.headerView];
    self.headerView.alpha = 0;
  
    // 添加返回按钮
    [self addBackButton];
    //添加分享按钮
    UIButton *shareButton = [UIButton buttonWithType:UIButtonTypeCustom];
    shareButton.frame = CGRectMake(kWidth - 64, 0, 64, 64);
    [shareButton setImage:[UIImage imageNamed:@"分享按钮.png"] forState:UIControlStateNormal];
    [shareButton addTarget:self action:@selector(shareClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:shareButton];
    //添加载入动画
    [self loadAniamtion];
    
    NSArray *array = @[@"热卖", @"更多详情", @"操作步骤"];
    for (int i = 0; i < 3; i++) {
        if ([self.type isEqualToString:array[i]]) {
            [self loadWebPageWithString:self.webUrl];
        }
    }
}

#pragma mark --- 加载动画 ---
// 添加加载动画
- (void)loadAniamtion {
    //添加加载动画
    self.animationLoad = [[YYAnimationIndicator alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-40, self.view.frame.size.height/2-40, 80, 80)];
    
    [self.animationLoad setLoadText:@"正在加载..."];
    [self.view addSubview:self.animationLoad];
    
   
}

- (void)startBtn {
    // 开始转动
    [self.animationLoad startAnimation];
}

/*
 当Type为YES时消失  NO时不消失
 */
-(void)StopBtn
{
    [self.animationLoad stopAnimationWithLoadText:@"finish" withType:YES];//加载成功
}

-(void)StopFailBtn
{
    [self.animationLoad stopAnimationWithLoadText:@"加载失败" withType:NO];//加载失败
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
    [self startBtn];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    [self StopBtn];
}



#pragma mark --- 分享 ---

- (void)shareClick:(UIButton *)button{
    
    
    if ([self.type isEqualToString:@"攻略"]) {
        WebStrategyModel *model = [self.webArray lastObject];
        NSURL *url = [NSURL URLWithString:model.cover_image_url];
        NSData *data = [NSData dataWithContentsOfURL:url];
        
        NSString *title = [NSString stringWithFormat:@"%@  %@",model.title,model.content_url];
        //屏幕旋转
        //[UMSocialConfig setSupportedInterfaceOrientations:UIInterfaceOrientationMaskLandscape];
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"55fd0ce3e0f55a305b002070"
                                          shareText:title
                                         shareImage:[UIImage imageWithData:data]
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,nil]
                                           delegate:self];

    }else {
        NSURL *url = [NSURL URLWithString:self.imageShare];
        NSData *data = [NSData dataWithContentsOfURL:url];
        
        NSString *title = [NSString stringWithFormat:@"%@  %@",self.nameShare,self.webUrl];
        //屏幕旋转
        //[UMSocialConfig setSupportedInterfaceOrientations:UIInterfaceOrientationMaskLandscape];
        [UMSocialSnsService presentSnsIconSheetView:self
                                             appKey:@"55fd0ce3e0f55a305b002070"
                                          shareText:title
                                         shareImage:[UIImage imageWithData:data]
                                    shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren,UMShareToDouban,nil]
                                           delegate:self];

    }
    
}


#pragma mark --- 数据解析 ---

//数据解析(攻略类)
- (void)reloadWebData {
    
    [LORequestManger GET:self.webUrl success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        
        WebStrategyModel *model = [WebStrategyModel shareDictionary:dic[@"data"]];
        [self.webArray addObject:model];
        [self loadWebPageWithString:model.content_url];
        self.shareUrl = model.content_url;
        [self addImageForHeader];

        [self.headerImage sd_setImageWithURL:[NSURL URLWithString:model.cover_image_url]];
        self.webView.scrollView.contentInset = UIEdgeInsetsMake(ImageHight, 0, -ImageHight, 0);
        [self StopBtn];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
    
}


#pragma mark --- 顶部形变图片 ---
//添加 顶部图片
- (void)addImageForHeader {
    
    self.headerImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"300 * 147"]];
    self.headerImage.frame = CGRectMake( 0, -ImageHight, self.view.frame.size.width, ImageHight);
    self.headerImage.backgroundColor = [UIColor whiteColor];
    //contentMode = UIViewContentModeScaleAspectFill时，高度改变宽度也跟着改变
    self.headerImage.contentMode = UIViewContentModeScaleAspectFill;
    self.headerImage.autoresizesSubviews = YES;
    [self.webView.scrollView addSubview:self.headerImage];
}

// 使顶部图片形变
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat y = scrollView.contentOffset.y;
    
        self.headerView.alpha = y /1000.0;

    if (y < -ImageHight) {
        CGRect frame = self.headerImage.frame;
        frame.origin.y = y;
        frame.size.height = -y;
        self.headerImage.frame = frame;
    }if (y> ImageHight) {
        self.webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        if ([self.type isEqualToString:@"攻略"] && ![self.webView canGoBack]) {
            self.headerView.titleLabel.text = @"攻略详情";
        }
        
    }else if (y < ImageHight && ![self.webView canGoBack] ){
        if ([self.type isEqualToString:@"攻略"]) {
            self.webView.scrollView.contentInset = UIEdgeInsetsMake(ImageHight, 0, -ImageHight, 0);
            self.webView.scrollView.bounces = YES;

        }
    }
}

//跳到下一个界面时取消顶部图片
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
    self.loadCount++;
    //NSLog(@"%lu",self.loadCount);
    if ([self.webView canGoBack]) {
        [self startBtn];
        self.webView.scrollView.bounces = NO;
        self.webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        self.headerView.titleLabel.text = @"商品详情";
    }else {
        
        if (self.loadCount < 2) {
            if ([self.type isEqualToString:@"攻略"]) {
                self.webView.scrollView.bounces = YES;
                self.headerView.titleLabel.text = @"攻略详情";
                
                self.webView.scrollView.contentInset = UIEdgeInsetsMake(ImageHight, 0, -ImageHight, 0);
            }if ([self.type isEqualToString:@"操作步骤"]) {
                self.webView.scrollView.bounces = NO;
                self.webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
                self.headerView.titleLabel.text = @"操作步骤";
            }
        }else {
            self.webView.scrollView.bounces = NO;
            self.webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
            self.headerView.titleLabel.text = @"商品详情";
        }
 
    }
    return YES;
}

//web载入数据
- (void)loadWebPageWithString:(NSString *)urlstring {
    
    NSURL *url = [NSURL URLWithString:urlstring];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:request];
    self.shareUrl = urlstring;
}


- (void)addBackButton {
    
    UIButton *backButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    backButton.frame = CGRectMake(0, 10, 54, 54);
    [backButton setBackgroundImage:[UIImage imageNamed:@"Entypo_e764(1)_64"] forState:(UIControlStateNormal)];
    [backButton addTarget:self action:@selector(backButton:) forControlEvents:(UIControlEventTouchUpInside)];
    [self.view addSubview:backButton];
    
}

- (void)backButton:(UIButton *)button {
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (NSMutableArray *)webArray {
    
    if (!_webArray) {
        _webArray = [[NSMutableArray alloc] init];
    }
    return _webArray;
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
